package com.neusoft.admin.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.neusoft.admin.entity.TableData;
import com.neusoft.admin.entity.feedbackData;
import com.neusoft.grid.entity.Grid;
import com.neusoft.grid.entity.Mission;
import com.neusoft.admin.method.GetColor;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.ToggleGroup;
import javafx.stage.Stage;

public class feedbackAssignViewControl {
    @FXML
    private TableView<TableData> tableView;
    @FXML
    private Button backButton;
    @FXML
    private RadioButton yes, no;
    @FXML
    private ToggleGroup group;
    @FXML
    private ComboBox<String> gridComboBox;
    private String feedbackId, feedbackerInfo, feedbackerContact, feedbackAddress, feedbackDescription, feedbackLevel,
            feedbackTime, feedbackAssign;
    private String backID, backName, backAddress, backDescription, backLevel, backTime, backPhone, backGrid, backYear,
            backMonth, backDate;
    private String gridName = "请选择网格员";
    private feedbackData feedbackData;
    private Map<String, String> map = new HashMap<>();
    private Mission missionData;

    @FXML
    public void initialize() throws IOException {
        group = new ToggleGroup();
        yes.setToggleGroup(group);
        no.setToggleGroup(group);
        no.setSelected(true);
        read();
        setTableView();
        setComboBox();
    }

    public feedbackAssignViewControl() {
    }

    public feedbackAssignViewControl(String feedbackId) {
        this.feedbackId = feedbackId;
    }

    public void backButtonAction() {
        Stage stage = (Stage) backButton.getScene().getWindow();
        stage.close();
    }

    public void read() {
        File missionFile = new File("src/com/neusoft/admin/data/mission.txt");
        File usersFile = new File("src/com/neusoft/admin/data/users.txt");
        try (BufferedReader br1 = new BufferedReader(new FileReader(missionFile));
                BufferedReader br2 = new BufferedReader(new FileReader(usersFile))) {
            if (!missionFile.exists()) {
                System.out.println("mission文件不存在");
                return;
            }
            if (!usersFile.exists()) {
                System.out.println("users文件不存在");
                return;
            }
            String line;
            if (feedbackId == null) {
                System.out.println("未查询到00");
                return;
            }
            while ((line = br1.readLine()) != null) {
                String[] parts = line.split(" ");
                if (parts[0].equals(feedbackId)) {
                    feedbackerInfo = parts[2];
                    feedbackerContact = parts[4];
                    feedbackAddress = parts[7] + parts[8] + parts[9];
                    feedbackLevel = parts[11];
                    feedbackDescription = parts[13];
                    feedbackTime = parts[15];
                    break;
                } else {
                    System.out.println("未查询到");
                }
            }
            while ((line = br2.readLine()) != null) {
                String[] parts = line.split(",");
                int nameIndex = parts[1].indexOf(" ");
                if (feedbackerInfo.equals(parts[1].substring(nameIndex + 1))) {
                    feedbackerInfo = "姓名:  " + feedbackerInfo + " " + parts[0] + " " + parts[2];
                    break;
                } else {
                    System.out.println("未查询到");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void setTableView() {
        final double TABLE_HEIGHT = 424;
        final double TABLE_HEADER_HEIGHT = 30;
        final double TABLE_PADDING = 10;
        ObservableList<TableData> data = FXCollections.observableArrayList(
                new TableData("公众监督反馈信息编号", feedbackId),
                new TableData("反馈者信息", feedbackerInfo),
                new TableData("反馈者联系电话", feedbackerContact),
                new TableData("反馈信息所在地址", feedbackAddress),
                new TableData("反馈信息描述", feedbackDescription),
                new TableData("预估等级", feedbackLevel),
                new TableData("反馈日期时间", feedbackTime));
        tableView.setItems(data);
        double rowHeight = (TABLE_HEIGHT - TABLE_HEADER_HEIGHT - TABLE_PADDING) / data.size();
        tableView.setFixedCellSize(rowHeight);

        // 假设第二列是目标列，索引为 1
        if (tableView.getColumns().size() > 1) {
            TableColumn<TableData, String> targetColumn = (TableColumn<TableData, String>) tableView.getColumns()
                    .get(1);
            targetColumn.setCellFactory(col -> new TableCell<TableData, String>() {
                @Override
                protected void updateItem(String item, boolean empty) {
                    super.updateItem(item, empty);
                    if (empty || item == null) {
                        setText(null);
                        setStyle("");
                    } else {
                        setText(item);
                        setAlignment(Pos.CENTER);
                        if (getIndex() == 5) {
                            setStyle(GetColor.getColor(item) + "-fx-font-size: 18px;");
                        } else {
                            setStyle("");
                        }
                    }
                }
            });
        }
        for (TableColumn<TableData, ?> column : tableView.getColumns()) {
            column.setSortable(false);
        }
        tableView.setStyle("-fx-font-size: 18px;");
    }

    public void assignButtonAction() throws FileNotFoundException, IOException {
        File missionFile = new File("src/com/neusoft/admin/data/mission.txt");
        try (BufferedReader br1 = new BufferedReader(new FileReader(missionFile))) {
            if (!missionFile.exists()) {
                System.out.println("mission文件不存在");
                return;
            }
            String line;
            int i = 1;
            if (feedbackId == null) {
                System.out.println("未查询到00");
                return;
            }
            while ((line = br1.readLine()) != null) {
                String[] parts = line.split(" ");
                if (parts[0].equals(feedbackId)) {
                    backName = parts[2];
                    backPhone = parts[4];
                    backGrid = parts[6] + parts[7];
                    backAddress = parts[9];
                    backLevel = parts[11];
                    backDescription = parts[13];
                    int yearIndex = parts[15].indexOf("年");
                    backYear = parts[15].substring(0, yearIndex);
                    int monthIndex = parts[15].indexOf("月");
                    backMonth = parts[15].substring(yearIndex + 1, monthIndex);
                    int dateIndex = parts[15].indexOf("日");
                    backDate = parts[15].substring(monthIndex + 1, dateIndex);
                    backTime = parts[15];
                    break;
                } else {
                    System.out.println("未查询到");
                }
                i++;
            }
            loadMissionsFromFile();
            backButtonAction();
            Mission mission = new Mission(backName, backPhone, backGrid, backAddress, backLevel, backDescription,
                    backYear,
                    backMonth, backDate,
                    feedbackId);
            Map<String, Mission> missionMap = new HashMap<>();
            missionMap.put(feedbackId, mission);
            writeMissions(missionMap, "src/com/neusoft/grid/data/mission.txt");
            System.out.println("已指派");
        }

    }

    public void writeMissions(Map<String, Mission> missions, String location) throws IOException {
        File file = new File(location);
        if (!file.exists()) {
            file.createNewFile();
        }
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))) {
            oos.writeObject(missions);
        }
    }

    private void setComboBox() throws IOException {
        File file = new File("src/com/neusoft/grid/data/grid.txt");
        Map<String, Grid> map = new HashMap<>();
        if (!file.exists() || file.length() == 0) {
            System.err.println("任务文件 grid.txt 不存在或者为空");
            file.createNewFile();
        }
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
            map = (Map<String, Grid>) ois.readObject();
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException(ex);
        }
        ObservableList<String> gridNameList = FXCollections.observableArrayList(gridName);
        for (Map.Entry<String, Grid> iterable_element : map.entrySet()) {
            Grid value = iterable_element.getValue();
            gridNameList.add(value.getName());
        }
        gridComboBox.setItems(gridNameList);
    }

    private void loadMissionsFromFile() {
        File file = new File("src/com/neusoft/admin/data/mission.txt");

        if (!file.exists()) {
            System.err.println("任务文件 mission.txt 不存在");
            return;
        }
        try {
            // 读取文件所有行
            List<String> lines = Files.readAllLines(file.toPath());
            int targetLineIndex = -1;
            for (int i = 0; i < lines.size(); i++) {
                String line = lines.get(i);
                String[] parts = line.split(" "); 
                if (parts.length > 0 && parts[0].equals(feedbackId)) {
                    targetLineIndex = i; // 找到匹配的反馈 ID，记录行索引
                    break;
                }
            }
            if (targetLineIndex >= 0 && targetLineIndex < lines.size()) {
                String line = lines.get(targetLineIndex);
                // 将 "未指派" 替换为 "已指派"
                String newLine = line.replace("未指派", "已指派");
                lines.set(targetLineIndex, newLine);
                // 将修改后的内容写回文件
                Files.write(file.toPath(), lines);
            }
        } catch (IOException e) {
            System.err.println("读取或写入任务文件失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
